<template>
	<view class="safe-area-inset-bottom">
		<view class="swip_header">
			<view class="slot-box">
				<view style="width: 100%;">
					<uni-search-bar v-model="queryParams.name" type="text" @confirm="handleQuery" @input="handleQuery" placeholder="请输入合同类型" />
				</view>
			</view>
			<view class="swiplist">
				<view>业务分类设置</view>
				<button size="mini" class="add_btn" @click="handleAdd"><i class="iconfont" style="color: #00a660;">&#xeaf3;</i>新增</span></button>
			</view>
		</view>
		
		<!-- 列表 -->
		<view v-if="contractBusinessTypeList != ''" class="listNameTop cardList">
		<uni-card :is-shadow="false" v-for="(item,index) in contractBusinessTypeList" :key="index">
			<p class="grid-integral">合同类型：{{item.contractTypeName}}</p>
			<p class="grid-integral">业务类型：{{item.name}}</p>
			<p class="grid-integral" v-if="item.remark != null">备注：{{item.remark}}</p>
			<p class="grid-hidden" v-else>备注：暂无</p>
			<p class="grid-integral" v-if="item.updateTime != null">更新时间：{{item.updateTime}}</p>
			<p class="grid-integral" v-else>更新时间：--</p>
			<view slot="actions" class="card-actions">
					<switch color="#00a660" style="transform:scale(0.7)" :checked="item.status == 1 ?true:false"
						@change="handleStatusChange(item)" v-if="item.isSystem == 1" disabled />
					<span v-else @click="handleStatusChange(item)">
						<switch color="#00a660" style="transform:scale(0.7)" :checked="item.status == 1 ?true:false"
							disabled />
					</span>
					<view class="flex_between">
						
					<view class="card-actions-item" @click="handleDelete(item,index)" v-if="item.isSystem == 0">
					  <text class="card-actions-item-text errorColor">删除</text>
					</view>
					<view class="card-actions-item" @click="handleAdd">
					  <text class="card-actions-item-text warningColor">克隆</text>
					</view>
			  <view class="card-actions-item" @click="getDetail(item.id)">
			    <text class="card-actions-item-text themeColor">编辑</text>
			  </view>
			  </view>
			</view>
		</uni-card>
		<!-- 加载更多 -->
		<uni-load-more color="#00a660" :status="loadStatus"/>
		</view>
		<!-- 暂无数据 -->
		<luanqingEmpty :show="true" text="没有更多数据啦" v-else />
		<!-- 修改 查看详情 -->
		<uni-popup ref="ListPopup" background-color="#fff" type="dialog">
			<uni-popup-dialog :before-close="true" :type="msgType" cancelText="取消" confirmText="确定" :title="title" @confirm="dialogConfirm" @close="closed">
			<template v-slot="content">
				<uni-forms ref="form" :rules="rules" :modelValue="form">
				<uni-forms-item label="合同类型" required name="contractTypeId">
					<uni-data-select v-model="form.contractTypeId" :localdata="contractType" :clear="false" placeholder="请选择合同类型"></uni-data-select>
					</uni-forms-item>	
				<uni-forms-item label="业务名称" required name="name">
					<uni-easyinput v-model="form.name" placeholder="请输入业务名称名称" :clearable="false"/>
				</uni-forms-item>
				<uni-forms-item label="排序" required name="sort">
					<uni-number-box v-model="form.sort" />
				</uni-forms-item>
				<uni-forms-item label="备注" name="remark">
					<uni-easyinput v-model="form.remark" placeholder="点击添加备注,最多300字!" :clearable="false" type="textarea"/>
				</uni-forms-item>
				</uni-forms>						
			</template>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {uniqueArr} from "@/utils";
	import {addContractBusinessType, delContractBusinessType, listDTOContractBusinessType,
	  updateContractBusinessType} from "@/api/ec/console/busiConfig/contractBusinessType";
	import {treeSelectAndStaff} from "@/api/ec/console/org/dept";
	import {listByCompanyId} from "@/api/ec/console/busiConfig/contractType";
	import luanqingEmpty from '@/components/luanqing-empty/luanqing-empty';
	export default {
		components:{luanqingEmpty},
		data() {
			return {
				total:0, //总条数
				loadStatus:'loading', //是否加载中 //加载样式：more-加载前样式，loading-加载中样式，nomore-没有数据样式
				deptOptions:null, //部门数据
				msgType:'info',
				contractType:[], //类型
				contractBusinessTypeList: [], // 合同类型列表
				title: "", // 弹出层标题
				// 查询参数
				queryParams: {
				  pageNum: 1,
				  pageSize: 10,
				  name: null,
				  contractTypeId: null,
				  status: null,
				},           
				form: {},
				rules: {
				name: {
					rules: [{
							required: true,
							errorMessage: '请输入合同类型名称'
						},{
							minLength: 2, maxLength: 12,
							errorMessage: '长度在2-12个，不能有特殊字符',
							trigger: "change"
						}]
					},
					contractTypeId: {
						rules: [{
							required: true,
							errorMessage: '请选择合同类型',
							trigger: "change"
						}]
					},
					sort: {
						rules: [{
							required: true,
							errorMessage: '请输入排序'
						}]
					},						
				},
			}
		},
		onLoad() {
			this.getList(true)
			// 获取合同类型
			this.getContractType()
		},
		//上拉触底函数
		onReachBottom() { 
		if (this.loadStatus != 'noMore' && this.total > this.contractBusinessTypeList.length) {
		  this.loadStatus = 'loading';
		  // 延迟500毫秒显示loading效果
		  setTimeout(() => {
		    // 执行查询的方法
		    this.getList(false);
		  }, 500)
		} else {
		  // 停止加载
		  this.loadStatus = 'noMore'
		}         
		},
		methods: {
			// 状态修改
			handleStatusChange(row){
				let text = row.status === 0 ? "启用" : "停用";
				this.$modal.confirm('确认要 " ' + text + ' " 吗？').then(function () {
					let status = row.status === 0?1:0
				  let data = {id: row.id, status:status};
				  return updateContractBusinessType(data);
				}).then(() => {
					this.getList(true);
				  this.$modal.msgSuccess(text + "成功");
				}).catch(function () {
				  row.status = row.status === 1 ? 0 : 1;
				});      
			},
			getDetail(id){
				uni.navigateTo({
					url:'./detail?id='+id
				})
			},
			/** 查询合同类型列表 */
			getContractType() {
			  listByCompanyId().then(response => {
			    this.contractType = [];
				response.data.forEach(item=>{
					this.contractType.push({text:item.name,value:item.id})
				})
			  });
			},
			/** 搜索 */
			handleQuery(){
				this.getList(true);      
			},
			/** 获取合同类型列表 */
			getList(reload) {
			  if (reload) {
			    this.queryParams.pageNum = 1;
			    this.loadStatus = 'more'
                this.$modal.loading();
			  }
			  listDTOContractBusinessType(this.queryParams).then(response => {
			    if (reload) {
			      uni.hideLoading()
			    }
			    this.total = response.total;
			    if (response.total > 0) {
			      const dataRows = response.rows;
				  response.rows.forEach(business=>{
				    let manageIdsInt=[]
				    if(!!business.manageIds){
				      let splitString = business.manageIds.split(",");
				      for (let i=0;i<splitString.length;i++){
				        manageIdsInt.push(parseInt(splitString[i]))
				      }
				    }
				    // 初始个人签署
				    if(business.isPersonSign!='-1' && !!business.isPersonSign){
				      business.isPersonSign=business.isPersonSign.split(",");
				    } else {
				      business.isPersonSign=["1"];
				    }
				    // 初始模板个人签署
				    if(!!business.contractTemplateSignPerson){
				      business.contractTemplateSignPerson=business.contractTemplateSignPerson.split(",");
				    } else {
				      business.contractTemplateSignPerson=["1"];
				    }
				    // 添加法人 管理员
				    let legalId = this.$store.getters.staffInfo.legalId;
				    let adminId = this.$store.getters.staffInfo.adminId;
				    if(legalId!=0 && legalId!=adminId){
				      manageIdsInt.push(this.$store.getters.staffInfo.legalId);
				    }
				    manageIdsInt.push(adminId);
				    business.manageIds = uniqueArr(manageIdsInt);
				    // 模板管理员
				    if(business.manageIds != null){
				    business.defaultManage = []
				    business.manageIds.forEach(item =>{
				         business.defaultManage.push({id:item,checked:true})
				    })  
				    }
				    this.contractBusinessTypeList = reload ? dataRows : this.contractBusinessTypeList.concat(dataRows);
				  })
			    } else {
			      this.contractBusinessTypeList = [];
			    }
			    // 判断数据是否加载完全
			    if (response.total <= this.contractBusinessTypeList.length) {
			      this.loadStatus = 'noMore'
			    }
			    // 页数+1
			    this.queryParams.pageNum++
			  }).catch(() => {
			    if (reload) {
			      uni.hideLoading()
			    }
			  });
			},
			/** 确定修改合同类型 */
			dialogConfirm(){
			    this.$refs.form.validate().then((res) => {
			      if (this.form.id != null) {
			            updateContractBusinessType(this.form).then(response => {
			              this.getList(true);
						  this.closed()
						  this.$modal.msgSuccess("修改成功");
			            });
			          } else {
			            addContractBusinessType(this.form).then(response => {
			              this.getList(true);
						  this.closed()
						  this.$modal.msgSuccess("新增成功");
			            });
			          }
			      });	        
			},
			/** 删除 */
			handleDelete(item,index){
				if (item.isSystem == 1) {
				    this.$modal.msgError("系统类型无法删除！");
				    return;    
				}
				var that = this
				// 删除
				uni.showModal({
					title: '系统提示',
					confirmColor:'#00a660',
					content: '是否删除该业务分类？',
					success: function (res) {
						if (res.confirm) {
							delContractBusinessType(item.id);
							that.getList(true)
							that.$modal.msgSuccess("删除成功");
						} else if (res.cancel) {
						}
					 },
				})
			},
			/** 新建合同类型 */
			handleAdd(){
				this.form = {
				        id: null,
				        name: null,
				        companyId: null,
				        contractTypeId: null,
				        sort: 0,
				      };
				this.title = '新增合同业务分类'
				this.$refs.ListPopup.open('center')
			},
			closed(){
				this.$refs.ListPopup.close()
			},
		}
	}
</script>

<style scoped lang="scss">
	::v-deep .uniui-bottom{
		color: #ccc !important;
	}
	// 分割线
	::v-deep .uni-forms-item__label{width: 150rpx !important;}
	::v-deep .uni-popup .uni-popup__wrapper{width: 90% !important;padding:0;}
	::v-deep .dropdown-item__content .list{right:20rpx}
</style>
